package com.neusoft.repository.service;

import com.mongodb.client.gridfs.model.GridFSFile;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * @program: repository
 * @description:
 * @author: dong.tl
 * @create: 2019-02-19 18:18
 **/
@Service
public class GridFsService {
    @Autowired
    private GridFsTemplate gridFsTemplate;
    @Autowired
    private MongoDbFactory mongoDbFactory;

    public String saveFile(MultipartFile multiportFile) throws Exception {

        if (multiportFile == null || StringUtils.isBlank(multiportFile.getOriginalFilename()))
            return null;

        // 获得提交的文件名
        String fileName = multiportFile.getOriginalFilename();
        // 获得文件输入流
        InputStream ins = multiportFile.getInputStream();
        // 获得文件类型
        String contentType = multiportFile.getContentType();
        // 将文件存储到mongodb中,mongodb 将会返回这个文件的具体信息
        ObjectId objectId = gridFsTemplate.store(ins, fileName, contentType);
        //将文件信息保存到关系型数据库中进行维护
        return objectId.toString();
    }

    public void deleteFile(String fileId) {
        if (StringUtils.isBlank(fileId))
            return;
        Query query = Query.query(Criteria.where("_id").is(fileId));
        // 查询单个文件
        GridFSFile gfsfile = gridFsTemplate.findOne(query);
        if (gfsfile != null) {
            gridFsTemplate.delete(query);
        }
    }
}
